
browserDomain <- jsonlite::read_json(
   path = "https://raw.githubusercontent.com/oguzhane/chrome-devtools-protocol-specs/main/prot/browser.domains.flatten.json"
)

jsDomain <- jsonlite::read_json(
   path = "https://raw.githubusercontent.com/oguzhane/chrome-devtools-protocol-specs/main/prot/js.domains.flatten.json"
)

domains <- modifyList(browserDomain, jsDomain)
commands <- domains[grep(".commands.", names(domains), fixed = TRUE)]
names(commands) <- sub(".commands.", ".", names(commands))

callbacks <- .rs.enumerate(commands, function(name, command) {
   
   # Generate function formals.
   formals <- vector("pairlist", length(command[["parameters"]]))
   if (length(formals)) {
      names <- vapply(command[["parameters"]], "[[", "name", FUN.VALUE = character(1))
      names(formals) <- names
   }
   
   # Generate function arguments.
   arguments <- lapply(names(formals), as.symbol)
   if (length(arguments))
      names(arguments) <- vapply(arguments, as.character, FUN.VALUE = character(1))
   
   # Generate a function body.
   parts <- c(
      as.symbol(".rs.automation.sendSynchronousRequest"),
      as.symbol("socket"),
      as.character(name),
      list(arguments)
   )
   
   body <- as.call(parts)
   
   # Put it all together.
   call("function", formals, call("{", body))
   
})

# Deparse and write to file.
contents <- deparse(callbacks, width.cutoff = 500)

# Give it a header.
template <- .rs.heredoc('
   #
   # SessionAutomationClient.R
   #
   # Copyright (C) 2025 by Posit Software, PBC
   #
   # Unless you have received this program directly from Posit Software pursuant
   # to the terms of a commercial license agreement with Posit Software, then
   # this program is licensed to you under the terms of version 3 of the
   # GNU Affero General Public License. This program is distributed WITHOUT
   # ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
   # MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
   # AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
   #
   #
   
   # .----------------------------------------------------------.
   # | This file was auto-generated by "generate-cdp-client.R". |
   # | Please do not modify this file by hand.                  |
   # `----------------------------------------------------------`
   
   .rs.addFunction("automation.createClient", function(socket)
   {
     %s
   })
')

rendered <- sprintf(template, paste(contents, collapse = "\n"))
writeLines(rendered, con = "src/cpp/session/modules/automation/SessionAutomationClient.R")
